<template>
    <div class="photo-gallery" v-if="photoArray.length > 0">
        <div :class="['photo-grid', 'columns-' + columns]">
            <div v-for="(photo, index) in displayedPhotos" :key="index" :class="imgVideoClass">
                <video v-if="isVideo(photo)" :src="photo" controls="controls" class="photo-image"></video>
                <my-img v-else :src="photo" class="photo-image" />
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        modelValue: String,
        max: {
            type: Number,
            default: 9
        }
    },
    computed: {
        photoArray() {
            return (this.modelValue || "").split(";").filter(x => x.length > 0).map(x => $store.getUrl(x));
        },
        displayedPhotos() {
            return this.photoArray.length > this.max ? this.photoArray.slice(0, this.max - 1) : this.photoArray;
        },
        columns() {
            let len = this.photoArray.length;
            if (len <= 3) return len;
            if (len == 4) return 2;
            return 3;
        },
        imgVideoClass() {
            if (!$mbh5 && this.displayedPhotos.length == 1 && this.isVideo(this.displayedPhotos[0])) {
                return "video-item";
            }
            return "photo-item";
        }
    },
    methods: {
        isVideo(fn) {
            let ix = fn.lastIndexOf(".");
            if (ix > -1) {
                let ext = fn.substring(ix).toLowerCase();
                return [".mp4", ".mov", ".avi", ".m4v", ".mpeg", ".ogm", ".wmv", ".mpg", ".webm", ".m4v", ".asx"].includes(ext);
            }
            return false;
        },
    }
}
</script>

<style scoped>
.photo-gallery {
    width: 100%;
}

.photo-grid {
    display: grid;
    gap: 8px;
    width: 100%;
}

.photo-grid.columns-1 {
    grid-template-columns: 1fr;
}

.photo-grid.columns-2 {
    grid-template-columns: repeat(2, 1fr);
}

.photo-grid.columns-3 {
    grid-template-columns: repeat(3, 1fr);
}

.photo-item {
    /* max-height: 300px; */
    overflow: hidden;
    border-radius: 8px;
    background-color: #f5f5f5;
}

.video-item {
    /* aspect-ratio: 4/3; */
    overflow: hidden;
    border-radius: 8px;
    background-color: #f5f5f5;
}

.photo-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.2s ease;
}

.photo-video {
    width: 100%;
    height: auto;
    transition: transform 0.2s ease;
}

.photo-image:hover {
    transform: scale(1.05);
}
</style>